/***
 * @author ing_cy   2010-11-26
 */
package com.framework;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.eportal.base.BaseDAO;
import com.framework.excelTools.DoExcel;
import com.framework.jqgrid.JqGridPager;
import com.framework.jqgrid.JsonDateValueProcessor;
import com.framework.jqgrid.JsonUtil;
import com.opensymphony.xwork2.ActionSupport;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

public class BaseAction extends ActionSupport implements ServletRequestAware,
        ServletResponseAware, SessionAware {
	
	private static Logger log = Logger.getLogger(BaseAction.class);

    /*struts2文件上传*/
    private File upload;
    private String uploadFileName;
    private String uploadContentType;

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }


//    public static String getCurrentLoginAgtCode(HttpServletRequest request) {
//        Object sessionValue = request.getSession().getAttribute("user");
//        String agtCode = "";
//        if (sessionValue instanceof Sysopt) {
//            agtCode = ((Sysopt) sessionValue).getUserName();
//        } else if (sessionValue instanceof Tagent) {
//            agtCode = ((Tagent) sessionValue).getAgtcode();///新系统不同之处
//        }
//        return agtCode;
//    }

    public static void responseBody(Map<String, Object> params) throws IOException {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        JSONObject json = JSONObject.fromObject(params);
        out.write(json.toString());
    }

    public static void responseBody(List<Object> data) throws IOException {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        JSONArray array = JSONArray.fromObject(data);
        out.write(array.toString());
    }

//    public static String getCurrentLoginUserName(HttpServletRequest request) {
//        Object sessionValue = request.getSession().getAttribute("user");
//        String uname = "";
//        if (sessionValue instanceof Sysopt) {
//            uname = ((Sysopt) sessionValue).getUserName();
//        } else if (sessionValue instanceof Tagent) {
//            uname = ((Tagent) sessionValue).getAgtloguser();
//        }
//        return uname;
//    }

//    public static String getCurrentLoginUserId(HttpServletRequest request) {
//        Object sessionValue = request.getSession().getAttribute("user");
//        String uid = "";
//        if (sessionValue instanceof Sysopt) {
//            uid = ((Sysopt) sessionValue).getSid() + "";
//        } else if (sessionValue instanceof Tagent) {
//            uid = ((Tagent) sessionValue).getSid() + "";
//        }
//        return uid;
//    }

    //lqf 2015-6-19
//    public static boolean isAdmin(HttpServletRequest request) {
//        Object sessionValue = request.getSession().getAttribute("user");
//        String uname = getCurrentLoginUserName(request);
//        return !(uname == null || !uname.equalsIgnoreCase("admin"));
//    }


    private static final long serialVersionUID = 1L;
    protected HttpServletResponse response;
    protected HttpServletRequest request;
    private static final Logger logger = (Logger) Logger
            .getLogger(BaseAction.class.getName());
    protected BaseDAO dao;

    public HttpSession getSession() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        return session;
    }

    public HttpServletRequest getRequest() {
        return ServletActionContext.getRequest();
    }

    public HttpServletResponse getResponse() {
        return ServletActionContext.getResponse();
    }

    public static Logger getLogger() {
        return logger;
    }

    public String getPath() {
        return ServletActionContext.getRequest().getContextPath();
    }

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }

    public String getRealPath() {
        return ServletActionContext.getRequest().getRealPath("/").replaceAll("\\\\", "/");
    }

    public void setSession(Map map) {

    }

    public BaseDAO getDao() {
        return dao;
    }

    public void setDao(BaseDAO dao) {
        this.dao = dao;
    }

    /**
     * jqGrid组件统一查询方法
     */
    public String jqGridQuery(HttpServletRequest request, List<?> listdata,
                              HttpServletResponse response, JqGridPager jqGridPager) throws Exception {

        try {
            if (request.getParameter("export") != null && "excel".equals(request.getParameter("export"))) {
                javax.servlet.ServletOutputStream servletoutputstream = response
                        .getOutputStream();
                response.reset();//必须加，不然保存不了临时文件
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=data.xls");
                if (jqGridPager.getExportCol() != null) {
                    DoExcel.cols = getText(jqGridPager.getExportCol());
                    DoExcel.colsname = getText(jqGridPager.getExportCol() + "_name");
                }
                DoExcel.excelExport(request, listdata, servletoutputstream);
                return null;
            } else {
                response.setContentType("text/xml; charset=UTF-8");//传输xml时要用html
                response.setCharacterEncoding("UTF-8");
                PrintWriter pw = response.getWriter();
                pw.write(JsonUtil.spanJson(request, listdata, jqGridPager));
            }
        } catch (Exception ex) {
        	log.error("", ex);
        }
        return null;

    }

    public String jqGridQueryMap(HttpServletRequest request, List<?> listdata,
                                 HttpServletResponse response, JqGridPager jqGridPager) throws Exception {
        return jqGridQueryMap(null, request, listdata, response, jqGridPager);
    }

    /**
     * jqGrid组件统一查询方法-map数据集
     */
    public String jqGridQueryMap(Class elementType, HttpServletRequest request, List<?> listdata,
                                 HttpServletResponse response, JqGridPager jqGridPager) throws Exception {

        try {
            if (request.getParameter("export") != null && "excel".equals(request.getParameter("export"))) {
                javax.servlet.ServletOutputStream servletoutputstream = response
                        .getOutputStream();
                response.reset();//必须加，不然保存不了临时文件
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=data.xls");
                if (jqGridPager.getExportCol() != null) {
                    DoExcel.cols = getText(jqGridPager.getExportCol());
                    DoExcel.colsname = getText(jqGridPager.getExportCol() + "_name");
                }
                DoExcel.excelMapExport(request, listdata, servletoutputstream);
                return null;
            } else {
                response.setContentType("text/xml; charset=UTF-8");//传输xml时要用html
                response.setCharacterEncoding("UTF-8");
                PrintWriter pw = response.getWriter();
                pw.write(JsonUtil.spanJson(elementType, listdata, jqGridPager, request));
            }


        } catch (Exception ex) {
        	log.error("", ex);
        }
        return null;

    }

    /**
     * 分页信息设置
     */
    public void setPage(HttpServletRequest request, JqGridPager jqGridPager) {
        jqGridPager.setId(request.getParameter("id"));
        jqGridPager.setPager(Integer.valueOf(request.getParameter("page") == null ? "0" : request.getParameter("page")));
        jqGridPager.setTotal(Integer.valueOf(request.getParameter("total") == null ? "0" : request.getParameter("total")));
        jqGridPager.setRows(Integer.valueOf(request.getParameter("rows") == null ? "0" : request.getParameter("rows")));
        jqGridPager.setPgButton(request.getParameter("pgButton"));
        jqGridPager.setSord(request.getParameter("sord"));
        jqGridPager.setSidx(request.getParameter("sidx"));
        jqGridPager.setExporttype(request.getParameter("exporttype"));
        jqGridPager.setIsexport(request.getParameter("export"));
    }

    /**
     * @param
     * @param
     * @param
     * @return
     * @throws Exception
     */
    public String autocomplete(HttpServletResponse response, List<Object[]> listdata, Integer[] labels, Integer[] values) throws Exception {

        try {
            response.setContentType("text/html; charset=UTF-8");//传输xml时要用html
            response.setCharacterEncoding("UTF-8");
            PrintWriter pw = response.getWriter();
            StringBuffer sb = new StringBuffer("[");
            int i = 0;
            if (listdata != null && listdata.size() > 0) {
                for (Object[] obj : listdata) {
                    String label = "";
                    String value = "";
                    for (Integer s : labels) {
                        label = label + "  " + obj[s - 1];
                    }
                    for (Integer v : values) {
                        value = value + obj[v - 1];
                    }
                    if (i == 0) {
                        sb.append("{\"label\": \"" + label + "\", \"value\": \"" + value + "\"}");
                    } else {
                        sb.append(",{\"label\": \"" + label + "\", \"value\": \"" + value + "\"}");
                    }
                    i++;
                }
            } else {
                sb.append("{\"label\": \"检索结果为空\", \"value\": \"no\"}");
            }

            sb.append("]");
            pw.write(sb.toString());
        } catch (Exception ex) {
        	log.error("", ex);
        }
        return null;

    }


    public String ajaxJuery(HttpServletResponse response, List<?> listdata) throws Exception {

        try {
            response.setContentType("text/json; charset=UTF-8");//传输xml时要用html
            response.setCharacterEncoding("UTF-8");
            PrintWriter pw = response.getWriter();
            StringBuffer sb = new StringBuffer();
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
            jsonConfig.registerJsonValueProcessor(Date.class,
                    new JsonDateValueProcessor());
            jsonConfig.registerJsonValueProcessor(java.lang.String.class, new JsonDateValueProcessor());
            JSONArray json = JSONArray.fromObject(listdata, jsonConfig);
            sb.append(json.toString());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("rows", listdata.size());
            map.put("data", json.toString());
            pw.write(JSONObject.fromObject(map).toString());
        } catch (Exception ex) {
        	log.error("", ex);
        }
        return null;

    }

    /**
     * 多选框选中
     *
     * @param name
     * @param value
     */
    public void checkboxvalue(String name, String value, String type) {
        if (value != null) {
            value = value.replaceAll(" ", "");
            if (type.equals("map")) {
                String[] values = value.split(",");
                Map<String, String> ttsmap = new TreeMap<String, String>();
                for (String val : values) {
                    ttsmap.put(val, val);
                }
                request.setAttribute(name, ttsmap);
            } else {
                String[] values = value.split(",");
                List ttsList = new ArrayList();
                for (String val : values) {
                    ttsList.add(val);
                }
                request.setAttribute(name, ttsList);
            }

        }
    }

    protected String invokeMethod(Object obj, String methodName) {
        try {
            return (String) obj.getClass().getMethod(methodName).invoke(obj);
        } catch (Exception e) {
            // TODO Auto-generated catch block
        	log.error("", e);
            return "error";
        }
    }

}
